'use strict'

import xss from 'xss'
import mongoose from 'mongoose'
import uuid from 'uuid'
import sms from '../service/sms'

const User = mongoose.model('User')

exports.verify = async (ctx, next) => {
  const phoneNumber = ctx.request.body.phoneNumber

  let user = await User.findOne({
    phoneNumber: phoneNumber
  }).exec()

  const verifyCode = sms.getCode()

  if (!user) {
    const accessToken = uuid.v4()

    user = new User({
      accessToken: accessToken,
      nickname: '牛人',
      avatar: 'https://res.cloudinary.com/rnappgougou/image/upload/v1550996910/avatar/defaut_avatar.jpg',
      phoneNumber: xss(phoneNumber),
      verifyCode: verifyCode
    })
  } else {
    user.verifyCode = verifyCode
  }

  try {
    user = await user.save()
  } catch (e) {
    ctx.body = {
      success: false
    }

    return next
  }

  // const msg = '您的注册验证码是：' + verifyCode
  // try {
  //   sms.send(user.phoneNumber, msg)
  // } catch (e) {
  //   console.log(e)

  //   ctx.body = {
  //     success: false,
  //     err: '短信服务异常'
  //   }

  //   return next
  // }

  ctx.body = {
    success: true,
    data: user.verifyCode
  }
}

exports.signUp = async (ctx, next) => {
  const verifyCode = ctx.request.body.verifyCode
  const phoneNumber = ctx.request.body.phoneNumber

  if (!verifyCode || !phoneNumber) {
    ctx.body = {
      success: false,
      err: '验证未通过'
    }

    return next
  }

  let user = await User.findOne({
    phoneNumber: phoneNumber,
    verifyCode: verifyCode
  }).exec()

  if (user) {
    user.verifyed = true
    user = await user.save()

    ctx.body = {
      success: true,
      data: {
        _id: user._id,
        accessToken: user.accessToken,
        nickname: user.nickname,
        avatar: user.avatar
      }
    }
  } else {
    ctx.body = {
      success: false,
      err: '验证未通过'
    }

    return next
  }

}

exports.update = async (ctx, next) => {
  const body = ctx.request.body
  let user = ctx.session.user

  const fields = 'avatar,gender,age,nickname,height'.split(',')
  fields.forEach(field => {
    if (body[field]) user[field] = body[field]
  })

  user = await user.save()

  ctx.body = {
    success: true,
    data: {
      _id: user._id,
      accessToken: user.accessToken,
      nickname: user.nickname,
      avatar: user.avatar,
      age: user.age,
      gender: user.gender,
      height: user.height
    }
  }
}
exports.getUserInfo = (ctx, next) => {
  ctx.body = {
    success: true
  }
}